package com.kingyea.mobilepolice.apimanage.system.aspect;

import com.alibaba.fastjson.JSON;
import com.kingyea.mobilepolice.system.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author Mr.Lin
 * @version v1.0.0
 * @description 系统AOP 用作统一返回结果处理 排除该切面注解为：@NotResult
 * @date Created in 2018-03-02 16:37:14
 */
@Component
@Aspect
@Order(-999)
public class ResultAspect {

    private static final Logger logger = LoggerFactory.getLogger(ResultAspect.class);

    //    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
//    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping) " +
//            "&& within(com.kingyea.mobilepolice..*.controller.*) " +
//            "&& !@annotation(com.kingyea.mobilepolice.system.aspect.NotResult)")
    @Pointcut("(@annotation(org.springframework.web.bind.annotation.RequestMapping) "
            + "|| @annotation(org.springframework.web.bind.annotation.PostMapping)"
            + "|| @annotation(org.springframework.web.bind.annotation.GetMapping)"
            + "|| @annotation(org.springframework.web.bind.annotation.PutMapping)"
            + "|| @annotation(org.springframework.web.bind.annotation.DeleteMapping)"
            + "|| @annotation(org.springframework.web.bind.annotation.PatchMapping)"
            + "|| @annotation(org.springframework.web.bind.annotation.Mapping)"
            + ")&& within(com.kingyea.mobilepolice..*.controller.*) "
            + "&& !@annotation(com.kingyea.mobilepolice.system.aspect.NotResult)")
    private void pointCutMethod() {

    }

    /**
     * 接口数据统一处理
     *
     * @param pjp
     * @return java.lang.Object
     * @author Mr.Lin
     * @date 2018-03-02 16:37:14
     */
    @Around("pointCutMethod()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Object obj = pjp.proceed();
        if (obj instanceof HttpEntity) {
            logger.error(obj.toString());
            return obj;
        }
        if (obj instanceof Result) {
            try {
                Result resultObj = JSON.parseObject(JSON.toJSONString(obj), Result.class);
                if (StringUtils.isEmpty(resultObj.getCode())) {
                    throw new Exception("非result,非异常,请忽略");
                }
                return resultObj;
            } catch (Exception e) {
            }
        }

        return Result.getSuccessResult(obj);
    }
}
